package com.java.code.utils.date;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtils {

    /**
     * 分
     */
    public static final long MINUTE_TTL = 60 * 1000l;
    /**
     * 时
     */
    public static final long HOURS_TTL = 60 * 60 * 1000l;
    /**
     * 半天
     */
    public static final long HALF_DAY_TTL = 12 * 60 * 60 * 1000l;
    /**
     * 天
     */
    public static final long DAY_TTL = 24 * 60 * 60 * 1000l;
    /**
     * 月
     */
    public static final long MONTH_TTL = 30 * 24 * 60 * 60 * 1000l;
    /**
     * 时间格式(yyyy-MM-dd)
     */
    public final static String DATE_PATTERN = "yyyy-MM-dd";
    /**
     * 时间格式(yyyy-MM-dd HH:mm:ss)
     */
    public final static String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
    public final static String YEAR = "yyyy";

    public static Date parseStr(String dataStr, String pattern) {
        SimpleDateFormat df = new SimpleDateFormat(pattern);
        try {
            Date parse = df.parse(dataStr);
//            Calendar instance = Calendar.getInstance();
//            instance.setTime(parse);
//
//            String ym = instance.get(Calendar.YEAR) + "" + instance.get(Calendar.MONTH);
//            System.out.println(ym);
            return parse;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String format(Date date, String pattern) {
        if (date != null) {
            SimpleDateFormat df = new SimpleDateFormat(pattern);
            return df.format(date);
        }
        return null;
    }

    public static String subDay(Date date, Integer days, String pattern) {
        Date sub = sub(date, days, Calendar.DAY_OF_MONTH);
        return format(sub, pattern);
    }

    public static Date sub(Date date, Integer time, int type) {
        Calendar rightNow = Calendar.getInstance();
        rightNow.setTime(date);
        rightNow.add(type, time);
        return rightNow.getTime();
    }

    public static Date subSeconds(Date date, Integer time) {
        return sub(date, time, Calendar.SECOND);
    }

    /**
     * 转时间戳 精确到秒
     *
     * @param date
     * @return
     */
    public static int secondTimestamp(Date date) {
        if (null == date) {
            return 0;
        }
        String timestamp = String.valueOf(date.getTime());
        int length = timestamp.length();
        if (length > 3) {
            return Integer.valueOf(timestamp.substring(0, length - 3));
        } else {
            return 0;
        }
    }
}

